﻿using AutoRegistDependency.Attributes;
using AutoRegistDependency.Interface;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyWpf.ViewModels.Base;
using HandyWpf.Views.Sys.Dictionary;
using Models.Entities.SystemEntities;
using Models.Queries.SystemQueries;
using Services.Base;
using Services.Sys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace HandyWpf.ViewModels.Sys
{
    [Component]
    public partial class DictionaryInfoViewModel : BasePageCRUDViewModel<DictionaryInfo, DictionaryQuery, IDictionaryService, int, DictionaryForm>
    {
        public DictionaryInfoViewModel(IEventBus eventBus, IBaseService<DictionaryInfo> baseService) : base(eventBus, baseService)
        {
            GetTreeData();
        }
        [ObservableProperty]
        private ObservableCollection<DictionaryInfo> treeData = new();
        public void GetTreeData()
        {
            TreeData.Clear();
            var service = (IDictionaryService)baseService;
            var list= service.GetTree();
            list.ForEach(t =>
            {
                TreeData.Add(t);
            });
        }

        public override string DialogToken => "DictionaryPage";

        public override DictionaryInfo GetEntityById(int primaryKey)
        {
            return baseService.Find(t=>t.Id== primaryKey);
        }

        public override (Expression<Func<DictionaryInfo, object>>, OrderByType)? GetOrderByExpression()
        {
            
            return (t=>t.Id, OrderByType.Desc);
        }

        public override Expression<Func<DictionaryInfo, bool>> GetQueryExpression()
        {
            Expressionable<DictionaryInfo> expressionable = new Expressionable<DictionaryInfo>();
            expressionable = expressionable.AndIF(Query.Id != null, t => t.Id == Query.Id)
                .AndIF(!string.IsNullOrWhiteSpace(Query.Name), t => t.Name.Contains(Query.Name))
                .AndIF(!string.IsNullOrWhiteSpace(Query.Value), t => t.Value.Contains(Query.Value))
                .AndIF(Query.ParentId != null, t => t.ParentId == Query.ParentId);
            return expressionable.ToExpression();
        }
        protected override void ClearForm()
        {
            Form = new DictionaryInfo()
            {
                ParentId = Query.ParentId
            };
        }

        public override void FormAdd()
        {
            base.FormAdd();
            GetTreeData();
        }
        public override void FormEdit()
        {
            base.FormEdit();
            GetTreeData();
        }
        [RelayCommand]
        public void SelectedItem(DictionaryInfo? select)
        {
            if (select != null)
            {
                Query.ParentId = select.Id;
                GetList();
            }
        }

    }
}
